<template>
  <div id="app">
    <router-view />
    <tabbar v-show="show"
            style="position:fixed">
      <tabbar-item :link="{path: '/', replace: true}"
                   :selected="this.active ===1">
        <img slot="icon"
             src="./assets/image/home.png">
        <img slot="icon-active"
             src="./assets/image/home_on.png">
        <span slot="label">首页</span>
      </tabbar-item>
      <tabbar-item :link="{path: '/my', replace: true}"
                   :selected="this.active ===2">
        <img slot="icon"
             src="./assets/image/my.png"
             width="5">
        <img slot="icon-active"
             src="./assets/image/my_on.png">
        <span slot="label">我的</span>
      </tabbar-item>
    </tabbar>
  </div>
</template>

<script>
import { Tabbar, TabbarItem } from 'vux';
import { mapActions, mapGetters } from 'vuex';
import * as API from './api';
export default {
  components: {
    Tabbar,
    TabbarItem
  },
  data () {
    return {
      show: true,
      active: 1,
      state: 0
    };
  },

  created () {
    // this.$http.get(API.user, {
    //   params: {
    //     openId: 'om4670a2bv4PxQJJl3jj2AwktkUY'
    //   }    }).then(res => {
    //   this.initUser(res.data)
    // }).catch(err => {
    //   console.log(err)
    // })
    // console.log('下面这个是是否授权的标记')
    // console.log(localStorage.getItem('token'))
    // alert(localStorage.getItem('token'))
    if (!localStorage.getItem('token')) {
      this.$wechatAuth.authorize()
      // alert('未授权用户,现在授权')
    } else {
      const { init } = JSON.parse(localStorage.getItem('vuex'));
      const { userInfo } = init;
      const { openId } = userInfo;
      this.$http
        .get(API.user, {
          params: {
            openId: openId
          }
        })
        .then(res => {
          if (res.data.code === 0) {
            // alert('缓存用户,更新信息')
            this.initUser(res.data);
          } else {
            // alert('无效用户,现在授权')
            localStorage.clear();
            this.$wechatAuth.authorize();
          }
        })
        .catch(err => {
          console.log(err);
          localStorage.clear();
        });
    }
  },
  methods: {
    ...mapActions(['initUser'])
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  watch: {
    $route (to) {
      const { name } = to;
      this.path = name;
      this.show = true;
      if (name === 'index') {
        this.active = 1;
      } else if (name === 'my') {
        this.active = 2;
      } else {
        this.show = false;
      }
    }
  }
};
</script>
<style lang="scss">
@import "./assets/style/rest.css";
@import "./assets/style/vux.scss";
</style>
